<?php

namespace app\api\controller;

use app\api\model\Admin as AdminModel;
use app\Request;

class Admin
{
    public function index(Request $request)
    {
        $limit = $request->param('limti') ? $request->param('limit') : 10;
        $page = $request->param('page') ? $request->param('page') : 1;
//        $aid=self::getAid();
        $db = new AdminModel();
        $field = 'id,username,create_time';
        $list = $db->limit($limit)->page($page)->field($field)->select();
        if ($list) {
            $count = $db->count('id');
            return json(['code' => 200, 'msg' => '成功', 'data' => $list, 'total' => $count]);
        } else {
            return json(['code' => 500, 'msg' => '暂无数据']);
        }

    }

    public function delete(Request $request)
    {
        $id = $request->param('id');
        $db = new AdminModel();
        if ($id == 1) {
            return json(['code' => 500, 'msg' => '超级管理员不能删除']);
        }
        $res = $db->where('id', $id)->delete();
        if ($res) {
            return json(['code' => 200, 'msg' => '删除成功']);
        } else {
            return json(['code' => 500, 'msg' => '删除失败']);
        }
    }


    public function add(\think\Request $request)
    {
        $data = $request->param();
        $db = new AdminModel();

        //新增
        $data['password'] = md5($data['password']);
        $res = $db->save($data);

        if ($res) {
            return json(['code' => 200, 'msg' => '操作成功']);
        } else {
            return json(['code' => 500, 'msg' => '操作失败']);
        }
    }

    public function update(\think\Request $request)
    {
        $data = $request->param();
        $db = new AdminModel();
        $info = $db->where('id', $data['id'])->find();
        if (isset($data['password']) && !empty($data['password'])) {
            if ($info['password'] === md5($data['password'])) {
                $data['password'] = $info['password'];
            } else {
                $data['password'] = md5($data['password']);
            }
        }
        $res = $db->update($data, ['id' => $data['id']]);

        if ($res) {
            return json(['code' => 200, 'msg' => '操作成功']);
        }else {
                return json(['code' => 500, 'msg' => '操作失败']);
            }

    }
}